const app = getApp()
const db = wx.cloud.database()
var that = this
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShowConfirm:false,
    picker1: ['准时', '外出培训', '禁食祷告', '外出服侍', '请假', '迟到', '放假','其他',],
    picker2: ['准时', '外出培训', '禁食祷告', '外出服侍', '请假', '迟到', '放假','其他',],
    index1: 0,
    index2: 0,
    punch:["点击打卡","点击补卡","已打卡","日期未到","请修改真实姓名","等待管理员开通","无历史记录"],
    punchcolor:["green","orange","grey","grey","red","orange","grey"],
    buttonState:"0",//[0,1,2,3]打卡，补卡，已打卡，日期未到
    punchHistory:[],
    dayStyle: [{ month: 'current', day: new Date().getDate(), color: 'white', background: '#AAD4F5' }, ],
    initDayStyle: [{ month: 'current', day: new Date().getDate(), color: 'white', background: '#AAD4F5' }, ],
    todayDayStyle: [],
  },
  prevMonth:function(e){this.inquire(e)},
  nextMonth:function(e){this.inquire(e)},
  dateChange:function(e){this.inquire(e)},
  inquire(e){
    if(!app.globalData.username){this.setData({isShowConfirm:true})}
    else if(!app.globalData.nickname){wx.showToast({title: '等待管理员确认',})}
    else{
    var currentYear  = e.detail.currentYear
    var currentMonth = e.detail.currentMonth
    app.globalData.id=app.globalData.nickname+currentYear.toString()+currentMonth
    var todayYear    = this.data.currentDate[2]
    var todayMonth   = this.data.currentDate[0]
    if(currentYear>todayYear||(currentYear==todayYear&&currentMonth>todayMonth))
      {this.setData({dayStyle:this.data.initDayStyle,buttonState:3})}
    else if(currentYear<2020||(currentYear==2020&&currentMonth<9))
      {this.setData({dayStyle:this.data.initDayStyle,buttonState:6})}
    else
      {this.getPunchHistory(e.detail.currentYear,e.detail.currentMonth)}
  }
  },
  judgeExist(currentYear,currentMonth,currentDay){
    console.log("更新按钮状态")
    var todayYear    = this.data.currentDate[2]
    var todayMonth   = this.data.currentDate[0]
    var todayDay     = this.data.currentDate[1]
    var exist=false
    for (var i = 0; i < this.data.punchHistory.length; ++i) {
      if(this.data.punchHistory[i].day==currentDay){exist=true}//先判断数据库有无记录，
      }
    if(currentYear==todayYear&&currentMonth==todayMonth&&currentDay>todayDay){this.setData({buttonState:3})}
    else if(exist==false){
      if(currentYear==todayYear&&currentMonth==todayMonth&&currentDay==todayDay){this.setData({buttonState:0})}//不存在，今天：请打卡0
      else{this.setData({buttonState:1})}//不存在，之前：请补卡1
    }
    else{this.setData({buttonState:2})}//存在：已打卡，默认2
  },
  dayClick: function (e) {
    //点击的日期是否需要补卡
    var currentYear  = e.detail.year
    var currentMonth = e.detail.month
    var currentDay = e.detail.day
    this.data.currentDay=currentDay
    var todayYear    = this.data.currentDate[2]
    var todayMonth   = this.data.currentDate[0]
    var todayDay   = this.data.currentDate[1]
    if(!app.globalData.username){this.setData({isShowConfirm:true})}
    else if(!app.globalData.nickname){wx.showToast({title: '等待管理员确认',})}
    else if(currentYear>todayYear||(currentYear==todayYear&&currentMonth>todayMonth)||(currentYear==todayYear&&currentMonth==todayMonth&&currentDay>todayDay)){this.setData({buttonState:3})}//未来：未到3
    else if(currentYear<2020||(currentYear==2020&&currentMonth<9))
      {this.setData({dayStyle:this.data.initDayStyle,buttonState:6})}
    else{
    this.judgeExist(currentYear,currentMonth,currentDay)
    }
    
    //给点击的日期设置一个背景颜色
    let clickDay = e.detail.day;
    let changeDay = `dayStyle[0].day`;
    let changeBg = `dayStyle[0].background`;
    this.setData({
      [changeDay]: clickDay,
      [changeBg]: "#AAD4F5",
      punchDay:clickDay
    })
  },


   /**
   * 打卡
  */
punch(){
  if(!app.globalData.username){this.setData({isShowConfirm:true})}
  else if(!app.globalData.nickname){wx.showToast({title: '等待管理员确认',})}
  else if(this.data.buttonState=="3"){wx.showToast({title: '日期未到',})}
  else if(this.data.buttonState=="2"){wx.showToast({title: '您已打卡',})}
  else if(this.data.buttonState=="6"){wx.showToast({title: '无历史记录',})}
  else if(this.data.buttonState=="0"||this.data.buttonState=="1"){
    wx.showToast({title: '打卡完成',})
    const db = wx.cloud.database()
    const _ = db.command
    db.collection('history').doc( app.globalData.id).update({
      data: {
        'dayStyle': _.unshift({color: 'white', month: "current",day: this.data.punchDay,  background: '#39b54a'}),
        "punchHistory":_.unshift({"day": this.data.punchDay,"first":this.data.picker1[this.data.index1],"second":this.data.picker2[this.data.index2]})
      },
      success:function(res){console.log("打卡成功")
    },
      fail: console.log("请等待")
    })
    this.setData({
      buttonState:"2",
      dayStyle: this.data.dayStyle.concat(  { month: 'current', day: this.data.punchDay, color: 'white', background: '#39b54a' }),
      punchHistory:this.data.punchHistory.concat({"day": this.data.punchDay,"first":"准时","second":"准时"})
    })
  }else{console.log("按键无效")}
},
PickerChange1(e) {
  this.setData({
    index1: e.detail.value
  })
},
PickerChange2(e) {
  
  this.setData({
    index2: e.detail.value
  })
},
onShow:function(){
  // this.getUser()
},
onLoad:function(){ 
    var that = this
    const db = wx.cloud.database()
    wx.cloud.callFunction({
      // 云函数名称
      name: 'login',
      success: function(res) {
      app.globalData.openid=res.result.openid
       that.getUser()
      },
      fail:console.log("信息获取中……")
    })
    this.data.currentDate=[new Date().getMonth()+1,new Date().getDate(),new Date().getFullYear()]
    this.data.punchDay=new Date().getDate()   
  },
getUser(){
  var that = this
    db.collection('user').where({
      _openid:app.globalData.openid
    })
    .get({})
    .then(res=>{
      if(res.data.length==1)//根据openid可以查询到用户
      {
        app.globalData.username = res.data[0].name
        app.globalData.nickname = res.data[0].nickname
        app.globalData.id=res.data[0].nickname+new Date().getFullYear().toString()+(new Date().getMonth()+1)
        if(!app.globalData.nickname){console.log("管理员未确认")
          that.setData({buttonState:5})}
        else{
          that.data.currentDay=that.data.currentDate[1]
          that.getPunchHistory(new Date().getFullYear(),new Date().getMonth()+1)
        }
      }else{console.log("未修改真实姓名")
      that.setData({buttonState:4})}
    })
  },
  getPunchHistory(year,month){
    this.data.punchHistory=[]
    this.data.dayStyle=[]
    var that = this
    var id= app.globalData.nickname+year.toString()+month
    const db = wx.cloud.database()
    db.collection('history').doc(id)
    .get({
    success: function(res) {
      console.log("获取成功")
      if(res.data.dayStyle){
      that.setData({
        dayStyle:that.data.initDayStyle.concat(res.data.dayStyle),
        punchHistory:res.data.punchHistory
      })
    }
    that.judgeExist(year,month,that.data.currentDay)
    },
    fail:function(res){
      console.log("本月无数据，新建中……")
      that.newRecord(year,month)
    }
  })
  },
  
  newRecord(year,month){
    this.setData({dayStyle:this.data.initDayStyle,buttonState:0})
    var id= app.globalData.nickname+year.toString()+month
    console.log(id)
    const db = wx.cloud.database()
    db.collection('history').add({
      data:{
        _id:id,
        username:app.globalData.username,
        month:month,
        year:year,
        dayStyle:[],
        punchHistory:[]
      }
    })
  },

  /**
   * 修改姓名弹窗
  */
  setValue: function (e) {
    this.setData({
      username: e.detail.value
    })
  },
  cancel: function () {
    var that = this
    that.setData({
      isShowConfirm: false,
    })
  },
  confirmAcceptance:function(){
    var that = this
    console.log(this.data.username)
    app.globalData.username=this.data.username
    that.setData({
      isShowConfirm: false,
      buttonState:5
    })
    wx.showToast({title: '修改成功',})
    db.collection("user").add({
      data:{name:this.data.username},
      success: function(res) {
        console.log("保存成功")
      },
      fail: function(res) {
        console.log("保存失败")
      }
    })
  },
})